package com.jfunit.java.helper;

import java.lang.reflect.Field;
import java.util.Map;

import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.jfunit.java.annotation.Inject;
import com.jfunit.java.util.ReflectionUtil;

/**
 * 依赖注入助手类
 * @author Administrator
 *
 */
public final class IocHelper {
    private static final Logger LOGGER = LoggerFactory.getLogger(IocHelper.class);

    static{
        System.out.println("======================================");
        System.out.println("IocHelper-0,start:");
        //获取所有Bean类与Bean实例之间的映射关系，简称Bean Map
        Map<Class<?>, Object> beanMap = BeanHelper.getBeanMap();
        System.out.println("IocHelper-1,beanMap:"+beanMap);
        if (MapUtils.isNotEmpty(beanMap)) {
            System.out.println("IocHelper-1,isNotEmpty:");
            //遍历Bean Map
            for (Map.Entry<Class<?>, Object> beanEntry : beanMap.entrySet()) {
                System.out.println("IocHelper-2,beanEntry:"+beanEntry);
                //从BeanMap中获取Bean类与Bean实例
                Class<?> beanClass = beanEntry.getKey();
                Object beanInstance = beanEntry.getValue();
                //获取Bean类定义的所有成员变量，简称Bean Field
                Field[] beanFields = beanClass.getDeclaredFields();
                System.out.println("IocHelper-2,beanFields:"+beanFields);
                if (ArrayUtils.isNotEmpty(beanFields)) {
                    //遍历Bean Field
                    for (Field beanField : beanFields) {
                        System.out.println("IocHelper-3,beanField:"+beanField);
                        //判断当前Bean Field是否还有Inject注解
                        if (beanField.isAnnotationPresent(Inject.class)) {
                            System.out.println("IocHelper-4,inject:"+beanField);
                            //在Bean中获取Bean Field对应的实例
                            Class<?> beanFieldClass = beanField.getType();
                            Object beanFieldInstance = beanMap.get(beanFieldClass);
                            if (beanFieldInstance !=null) {
                                System.out.println("通过反射初始化BeanField的值:beanField:"+beanField);
                                //通过反射初始化BeanField的值 
                                ReflectionUtil.setField(beanInstance, beanField, beanFieldInstance);
                            }
                        }
                    }
                }
            }
        }
    }
}
